package Offer.q07_buildTree;

import CommonClass.Common.TreeNode;

import java.util.HashMap;
import java.util.Map;

public class Solution {
    Map<Integer, Integer> map = new HashMap<>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length == 0){
            return null;
        }
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return dfs(preorder, inorder, 0, preorder.length - 1, 0, inorder.length);
    }

    private TreeNode dfs(int[] preorder, int[] inorder, int pre_l, int pre_r, int in_l, int in_r) {
        if (pre_l > pre_r) {
            return null;
        }

        TreeNode root = new TreeNode(preorder[pre_l]);
        int root_index = map.get(preorder[pre_l]);
        int left_len = root_index - in_l;

        root.left = dfs(preorder, inorder, pre_l + 1, pre_l + left_len, in_l, in_l + left_len - 1);
        root.right = dfs(preorder, inorder, pre_l + left_len + 1, pre_r, in_l + left_len + 1, in_r);

        return root;
    }
}
